package linter.controller.model;


import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import linter.POJO.DO.Model;
import linter.POJO.DTO.ModelDTO;
import linter.POJO.DTO.UserDTO;
import linter.custom.ResultVO;
import linter.service.ModelDataDisposeService;
import linter.service.ModelService;
import linter.service.UserFileService;
import linter.service.UserService;
import linter.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Objects;

import static linter.custom.Constant.*;
import static linter.custom.CustomResultType.*;
import static linter.utils.ModelUtils.generateUUID;
import static linter.utils.ModelUtils.getModelNameByNumber;

/**
 * @author 北煜
 */
@Slf4j
@RestController
@Api(tags = "文件接口")
@RequestMapping("/File")
public class FileController {

    @Resource
    UserService userService;
    @Resource
    UserFileService userFileService;
    @Resource
    ModelService modelService;
    @Resource
    ModelDataDisposeService modelDataDisposeService;

    @GetMapping("/show/getUserByUsername/{username}")
    @ApiOperation("根据用户名查找用户")
    public ResultVO<UserDTO> getUserByUsername(@PathVariable String username) {
        UserDTO userDTO = userService.getUserByUsername(username);
        return ResultVO.success(userDTO);
    }

    @PostMapping("/selAllModel")
    @ApiOperation("获取所有模型")
    public ResultVO<PageInfo<Model>> selAllModel() {
        String username = JwtUtils.getUserName((String) SecurityUtils.getSubject().getPrincipal());
        Long uuid = userService.getIdByUsername(username);
        if (uuid != null) { return ResultVO.success(modelService.getAllModel()); }
        return ResultVO.error(USER_NOT_EXIST);
    }

    @PostMapping("/selModel")
    @ApiOperation("模糊查询模型")
    public ResultVO<?> selModel(@RequestBody ModelDTO modelDTO) {
        String username = JwtUtils.getUserName((String) SecurityUtils.getSubject().getPrincipal());
        Long uuid = userService.getIdByUsername(username);
        if (uuid != null) {
            return ResultVO.success(modelService.selModel(modelDTO.getModelName(),
                    modelDTO.getModelNub(), modelDTO.getModelIntroduce()));
        }
        return ResultVO.error(USER_NOT_EXIST);
    }

    @PostMapping("/upload")
    @ApiOperation("文件上传接口")
    public ResultVO<String> upload(@RequestParam("file") MultipartFile file, String fileName, Integer modelType, String fileType) {
        String username = JwtUtils.getUserName((String) SecurityUtils.getSubject().getPrincipal());
        Long uuid = userService.getIdByUsername(username);
        if (uuid != null) {
            //构造一个带指定Region对象的配置类
            Configuration cfg = new Configuration(Region.region2());
            cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
            UploadManager uploadManager = new UploadManager(cfg);
            Auth auth = Auth.create(ACCESS_KEY_QINIU, SECRET_KEY_QINIU);
            String bucketName = BUCKET_NAME_QINIU;
            String baseUrl = "http://qiniuyun.linter.top";
            try {
                // 验证模型类型有效性
                String type = getModelNameByNumber(modelType);
                if (!MODEL_TYPE_NOT_EXIST.equals(type)) {
                    // 使用用户ID和原文件名构建七牛云存储的key
                    String key = "data/ModelUser/" + type + "/" + fileType + "/" + generateUUID() + "_" + fileName;
                    String url = baseUrl+"/"+key;
                    String save = userFileService.saveById(uuid, url, type, fileType);
                    if (Objects.equals(save, SAVE_NOT_ERROR)){ return ResultVO.error(SAVE_NOT_ERROR); }

                    // 直接从MultipartFile对象上传文件内容到七牛云
                    byte[] fileContent = file.getBytes();
                    try (ByteArrayInputStream inputStream = new ByteArrayInputStream(fileContent)) {
                        String upToken = auth.uploadToken(bucketName);
                        Response response = uploadManager.put(inputStream, key, upToken, null, null);
                        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

                        if (response.statusCode == RES_SUCCESS) {
                            return ResultVO.success(putRet.hash, UPLOAD_SUCCESS);
                        } else {
                            throw new RuntimeException(UPLOAD_ERROR + ": " + response.bodyString());
                        }
                    }
                } else {
                    return ResultVO.error(MODEL_TYPE_ERROR_MSG);
                }
            } catch (QiniuException ex) {
                throw new RuntimeException(UPLOAD_COURSE_ERROR + ": " + ex.getMessage(), ex);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            return ResultVO.error(USER_NOT_EXIST);
        }
    }

    @PostMapping("/uploadModelDataDispose")
    @ApiOperation("上传模型数据")
    public ResultVO<?> uploadModelDataDispose(@RequestParam(value = "file") MultipartFile file, String dataName){
        String username = JwtUtils.getUserName((String) SecurityUtils.getSubject().getPrincipal());
        Long uuid = userService.getIdByUsername(username);
        if (uuid != null) { return ResultVO.success(modelDataDisposeService.uploadModelDataDispose(file, dataName, uuid)); }
        return ResultVO.error(USER_NOT_EXIST);
    }

}

